package com.food.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.food.admin.entity.AccountInfo;
import com.food.admin.exception.accountException.AccountException;
import com.food.admin.form.AccountInfoUpdateForm;
import com.food.admin.mapper.AccountInfoMapper;
import com.food.admin.model.ConstantData;
import com.food.admin.service.AccountInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.food.admin.util.JwtUtil;
import com.food.admin.util.RedisUtil;
import com.food.admin.util.WebUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import static com.food.admin.exception.accountException.AccountExceptionCode.ACCOUNT_INFO_NOT_READY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 帅得一
 * @since 2023年06月13日
 */
@Service
public class AccountInfoServiceImpl extends ServiceImpl<AccountInfoMapper, AccountInfo> implements AccountInfoService {

    @Autowired
    private AccountInfoMapper accountInfoMapper;
    @Autowired
    private RedisUtil redisUtil;
    @Override
    public AccountInfo updateAccountInfo(AccountInfoUpdateForm form) throws Exception {
        AccountInfo accountInfo = BeanUtil.toBean(form, AccountInfo.class);
        if(form.getAccountSex()== ConstantData.ACCOUNT_SEX_MAN) accountInfo.setAccountSexName("男");
        if(form.getAccountSex()== ConstantData.ACCOUNT_SEX_WOMAN) accountInfo.setAccountSexName("女");
        accountInfo.setAccountInfoId(form.getAccountInfoId());
        accountInfo.setAccountId(form.getAccountId());
        accountInfo.setAccountPhone(form.getAccountPhone());
        accountInfo.setAccountIdCard(form.getAccountIdCard());
        accountInfo.setAccountSex(form.getAccountSex());
        accountInfo.setAccountRealName(form.getAccountRealName());
        accountInfoMapper.updateById(accountInfo);
        return accountInfo;
    }

    @Override
    public AccountInfo showMyInfo() throws Exception {
        String accessToken = WebUtil.getRequest().getHeader("accessToken");
        String refreshToken = redisUtil.get(accessToken);
        Integer accountId = JwtUtil.getUserId(refreshToken);
        QueryWrapper<AccountInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account_id",accountId);
        AccountInfo accountInfo = accountInfoMapper.selectOne(queryWrapper);
        if(accountInfo==null){
            throw new AccountException(ACCOUNT_INFO_NOT_READY);
        }
        return accountInfo;
    }




}
